package com.school.basic.service.impl;

import com.school.basic.entity.ClassInfo;
import com.school.basic.entity.StudentInfo;
import com.school.basic.entity.TeacherInfo;
import com.school.basic.repository.ClassInfoRepository;
import com.school.basic.repository.StudentInfoRepository;
import com.school.basic.repository.TeacherInfoRepository;
import com.school.basic.service.ClassInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ClassInfoServiceImp implements ClassInfoService {
    @Autowired
    ClassInfoRepository classInfoRepository;
    @Autowired
    TeacherInfoRepository teacherInfoRepository;
    @Autowired
    StudentInfoRepository studentInfoRepository;

    /**
     * 增加
     * @param classInfo
     * @return
     */
    @Override
    public ClassInfo addClassInfo(ClassInfo classInfo) {
        ClassInfo result = new ClassInfo();
        try {
            boolean isExist = classInfoRepository.existsByClassNameAndGrade(classInfo.getClassName(),classInfo.getGrade());
            if(isExist)
                throw new RuntimeException("班级已存在!");
            classInfo.setCreateDate(new Date());
            classInfo.setUpdateDate(new Date());
            result = classInfoRepository.saveAndFlush(classInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return result;
    }

    /**
     * 查询所有
     * @param
     */
    @Override
    public List<ClassInfo> findAll() {
        return classInfoRepository.findAll();
    }

    /**
     * 修改
     * @param classInfo
     * @return
     */
    @Override
    public ClassInfo updateClassInfo(ClassInfo classInfo) {
        classInfo.setUpdateDate(new Date());
        return classInfoRepository.saveAndFlush(classInfo);
    }

    /**
     * 班级人数更新
     * @param id,total
     */
    @Override
    public void updateTotal(String id,String total) {
        ClassInfo classInfo;
        try {
            classInfo = classInfoRepository.findById(Integer.valueOf(id)).get();
            classInfo.setTotal(total);
            classInfoRepository.saveAndFlush(classInfo);
            String [] split = total.split(",");
            String className = classInfo.getClassName();
            for(String s : split){
                StudentInfo studentInfo = studentInfoRepository.findById(Integer.valueOf(s)).get();
                studentInfo.setGrade(classInfo.getGrade());
                studentInfo.setClassId(Integer.valueOf(id));
                studentInfo.setClassName(className);
                studentInfoRepository.saveAndFlush(studentInfo);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看详情
     * @param id
     */
    @Override
    public ClassInfo getDetailsById(String id) {
        return classInfoRepository.findById(Integer.valueOf(id)).get();
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteClassInfo(String id) {
        ClassInfo classInfo;
        try {
            classInfo = classInfoRepository.findById(Integer.valueOf(id)).get();
            classInfoRepository.delete(classInfo);
            studentInfoRepository.deleteAllByClassId(id);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除
     * @param idList
     */
    @Override
    public void deleteClassInfoList(String idList) {
        String[] split = idList.split(",");
        List<Integer> list = new ArrayList<>();
        for (String s : split) {
            list.add(Integer.parseInt(s));
            studentInfoRepository.deleteAllByClassId(s);
        }
        classInfoRepository.deleteClassInfosByIdIn(list);
        studentInfoRepository.deleteAllByClassIdIn(list);
    }

    /**
     * 根据条件分页查询
     * @param classInfo,page,size
     */
    @Override
    public Page<ClassInfo> specificPageQueryClassInfoList(ClassInfo classInfo, int page, int size) {
        Specification querySpecification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if(classInfo != null)
                {
                    Integer schoolId = classInfo.getSchoolId();
                    Integer grade = classInfo.getGrade();
                    String className = classInfo.getClassName();
                    String headMasterName = classInfo.getHeadMasterName();
                    if(schoolId != null){
                        predicates.add(criteriaBuilder.equal(root.get("schoolId").as(Integer.class),schoolId));
                    }
                    if(grade != null){
                        predicates.add(criteriaBuilder.equal(root.get("grade").as(Integer.class),grade));
                    }
                    if (!StringUtils.isEmpty(className))
                    {
                        predicates.add(criteriaBuilder.like(root.get("className").as(String.class),'%' + className + '%'));
                    }
                    if (!StringUtils.isEmpty(headMasterName))
                    {
                        predicates.add(criteriaBuilder.like(root.get("headMasterName").as(String.class),'%' + headMasterName + '%'));
                    }
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        PageRequest pageRequest = PageRequest.of(page-1, size, Sort.by(Sort.Direction.DESC,"updateDate"));
        return classInfoRepository.findAll(querySpecification,pageRequest);
    }

    /**
     * 根据学校ID查询所有
     * @param schoolId
     */
    @Override
    public List<ClassInfo> findAllBySchoolId(Integer schoolId){
        return classInfoRepository.findAllBySchoolId(schoolId);
    }

}
